
var Member = function() {

    var datalist_url = $('.datalist_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var detail_url = $('.detail_url').val();
    var redirect_url = $('.redirect_url').val();
    var save_url = $('.save_url').val();
    var checkNum_url = $('.checkNum_url').val();


    // Handles Bootstrap switches
    var init_bootstrapSwitch = function() {
        if (!$().bootstrapSwitch) {
            return;
        }
        $('.make-switch').bootstrapSwitch();
    };

    var initTable = function() {
        var table = $('#data-table');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: datalist_url,
                },
                "autoWidth": false,
                "columns": [
                    {
                        "data": "avatar",
                        "render": function(data, type, row, meta) {
                            if(data){
                                return '<a href="'+data+'" target="_blank"><img src="'+data+'" style="width: 40px;height: 40px;"/></a>';
                            }else{
                                if(row.gender == 2 || row.gender == '女'){
                                    return '<img src="/public/static/admin/img/default_female.png" alt="" style="width: 40px;height: 40px;" />';
                                }else{
                                    return '<img src="/public/static/admin/img/default_male.png" alt="" style="width: 40px;height: 40px;" />';
                                }
                            }
                        }
                    },
                    {"data": "name"},
                    {"data": "gender"},
                    {"data": "mobile"},
                    {"data": "identityNumber"},
                    {"data": "ethnicId"},
                    {"data": "area"},
                    {
                        "data": "memberType",
                        "render": function(data, type, row, meta) {
                            switch (data) {
                                case 1:
                                    data = '本地居民';
                                    break;
                                case 2:
                                    data = '外来人口';
                                    break;
                                case 3:
                                    data = '流动人口';
                                    break;
                                default: break;
                            }

                            return data;
                        }
                    },
                    {
                        "data": "shenheStatus",
                        "render": function(data, type, row, meta) {
                            return data == 1 ? '认证' : '后台添加';
                        }
                    },
                    {
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var html = '';
                            html += '<a href="'+edit_url+'?id='+row.id+'" type="button" class="btn btn-success">编辑</a>';
                            if(row.id == ADMININFO.memberId){
                                html += '<button type="button" class="btn btn-danger" disabled="disabled">删除</button>';
                            }else{
                                html += '<button type="button" class="btn btn-danger delete-btn">删除</button>';
                            }

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": true,
                //"stateSave": false,
                "stateSaveParams": function (settings, data) {
                    var search = data.search.search;
                    //console.log(data);
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }
                },
                "order": [
                    [1, "desc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [0, 2, 4, 5, 6, 7, 8, 9]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                    var city = $('input[name=city]').val();
                    if(city){
                        //$("#city").find("option:contains('"+city+"')").attr("selected", true);
                        get_xian($("#city"));
                    }
                    if ($('#memberType').val() && $('#memberType').val() != 1) {
                        $('.town-div').hide();
                    } else {
                        $('.town-div').show();
                    }
                }
            });
        }

        // 筛选
        /*$('#doSearch').on('click', function(event){
            var param = $('#searchForm').serializeObject();

            tableSearch(table, param);
        });*/

        // 删除
        table.on('click', '.delete-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要删除这条数据？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();

            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    layer.close(index);
                    var url = delete_url;
                    var data = {'id':id};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType : 'json',
                        success: function (data) {
                            layer.msg(data.msg);
                            if(data.code == 1){
                                _this.parents('tr').remove();
                            }
                        }
                    });
                }
            );
        });
    };

    var tableSearch = function(table, params) {

        table.DataTable().search(JSON.stringify(params)).draw();
    };

    // 详情页初始化
    var initDetail = function() {
        if($('#ajax-form').length > 0){
            init_memberType();
            init_isHouseholder();
        }
    };

    // 初始化 人口类型
    var init_memberType = function() {
        var memberType = $('.member-type').find('input[name=memberType]:checked').val();
        if(memberType == 1){
            $('.belong-location').show();
        }else{
            $('.belong-location').hide();
        }
    };

    // 初始化 是否为户主
    var init_isHouseholder = function() {
        var isHouseholder = $("input[name='isHouseholder']:checked").val();
        if(isHouseholder == 1) {
            $('.related-householder').hide();
        } else {
            $('.related-householder').show();
        }
    };


    // 表单提交
    var submitForm = function(btnObj) {
        var form = document.getElementById("ajax-form");
        var _this = btnObj;

        // 选择为本地居民
        if(form.memberType.value.trim() == 1) {
            if(form.villageId.value == '0' && form.townId.value == '0') {
                layer.msg('请选择乡镇');
                return;
            }
        } else {
            form.cityId.value = '';
            form.xianId.value = '';
            form.townId.value = '';
            form.villageId.value = '';
        }
        if(form.name.value.trim()=='') {
            layer.msg('姓名不能为空');
            form.name.focus();
            return;
        }
        if(form.identityNumber.value.trim()=='') {
            layer.msg('身份证号不能为空');
            form.identityNumber.focus();
            return;
        }
        /*if(!checkIdentity(form.identityNumber.value)){
            layer.msg('身份证号格式不正确');
            form.identityNumber.focus();
            return;
        }*/
        var mobile = $('#mobile').val();
        /*if(mobile.trim() == ''){
            layer.msg('手机号不能为空');
            form.mobile.focus();
            return;
        }*/
        if(mobile){
            var mobile_reg = /^1(3|4|5|6|7|8|9)[0-9]\d{8}$/;
            if(!mobile_reg.test(mobile)){
                layer.msg('手机号格式不正确');
                form.mobile.focus();
                return;
            }
        }

        // 选择为非户主
        if(form.isHouseholder.value == 2){
            if(!form.householderId.value || form.householderId.value == 0) {
                layer.msg('请选择户主');
                return;
            }
            if(form.relatedHouseholder.value === '0') {
                layer.msg('请选择与户主的关系');
                return;
            }
        } else {
            form.householderId.value = '';
            form.relatedHouseholder.value = 0;
        }

        var _data = $(form).serializeObject();
        //console.log(_data);
        _this.prop("disabled", true);
        $.ajax({
            url : save_url,
            type : 'post',
            dataType : 'json',
            contentType : "application/json; charset=utf-8",
            data : JSON.stringify(_data),
        }).done(function(data) {
            if (data.code == 1) {
                layer.msg('保存成功');
                window.location.href = data.url; //加载页面数据
            } else if (data.code === 0 ) {  // 错误
                _this.prop("disabled", false);
                layer.msg(data.msg);
            }
        });
    };


    return {
        init: function() {
            init_bootstrapSwitch();
            initTable();
            initDetail();

            this.onEvent();
        },

        onEvent : function(){

            // Table 筛选
            $('#doSearch').on('click', function(event){
                var table = $('#data-table');
                if(!table.is(':visible')){
                    table = $('#checkdata-table');
                }

                var param = $('#searchForm').serializeObject();
                tableSearch(table, param);
            });

            $('#memberType').on('click', function(){
                var memberType = $(this).val();
                if (memberType != 1) {
                    $('.town-div').hide();
                } else {
                    $('.town-div').show();
                }
            });

            // 切换 人口类型
            $('.member-type').on('click', function(){
                init_memberType();
            });
            // 切换 是否为户主
            $('.switch-isHouseholder').on('click', function(){
                init_isHouseholder();
            });


            // 模板下载
            $('#download_template').on('click', function(){
                var url = $(this).data('url');
                if(ADMININFO.type == 0) {
                    var cityId = $('#searchForm').find('select[name=cityId]').val();
                    var xianId = $('#searchForm').find('select[name=xianId]').val();
                    var townId = $('#searchForm').find('select[name=townId]').val();
                    var villageId = $('#searchForm').find('select[name=villageId]').val();
                } else {
                    var cityId = ADMININFO.cityId;
                    var xianId = ADMININFO.xianId;
                    var townId = ADMININFO.townId;
                    var villageId = ADMININFO.villageId;
                }
                if(!townId || townId == 0){
                    layer.msg('请选择镇');
                    return false;
                }

                var $form = '<form id="export_form" action="'+url+'" method="post" style="display: none;">';
                $form += '<input name="cityId" value="'+cityId+'" >';
                $form += '<input name="xianId" value="'+xianId+'" >';
                $form += '<input name="townId" value="'+townId+'" >';
                $form += '<input name="villageId" value="'+villageId+'" >';
                $form += '</form>';
                if($(document).find('#export_form').length){
                    $(document).find('#export_form').remove();
                }
                $(document.body).append($form);
                // 提交表单，实现下载
                $(document).find('#export_form').submit();
            });

            // 批量导入
            $('#import_csv').on('click', function(){
                var csv_file = $('input[name=csv_file]').val();
                var point = csv_file.lastIndexOf(".");

                var type = csv_file.substr(point);
                type = type.toLowerCase();
                if(type != ".csv" && type != ".xls" && type != ".xlsx"){
                    layer.msg('请选择csv, xls, xlsx文件');
                    return false;
                }

                var url = $('#import_form').attr('action');
                var data = new FormData();
                var csv_file = document.getElementById('csv_file').files[0];
                data.append('csv_file', csv_file);

                layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    //dataType : 'json',
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        layer.closeAll('loading'); // 关闭loading
                        layer.msg(data.msg);
                        if(data.status == 1){
                            window.location.reload();
                        }
                    }
                });
                return false;
            });

            // 批量导出
            $('#export_csv').on('click', function(){
                var url = $(this).data('url');
                if(ADMININFO.type == 0) {
                    var cityId = $('#searchForm').find('select[name=cityId]').val();
                    var xianId = $('#searchForm').find('select[name=xianId]').val();
                    var townId = $('#searchForm').find('select[name=townId]').val();
                    var villageId = $('#searchForm').find('select[name=villageId]').val();
                } else {
                    var cityId = ADMININFO.cityId;
                    var xianId = ADMININFO.xianId;
                    var townId = ADMININFO.townId;
                    var villageId = ADMININFO.villageId;
                }
                var name = $('#searchForm').find('input[name=name]').val();

                var $form = '<form id="export_form" action="'+url+'" method="post" style="display: none;">';
                $form += '<input name="cityId" value="'+cityId+'" >';
                $form += '<input name="xianId" value="'+xianId+'" >';
                $form += '<input name="townId" value="'+townId+'" >';
                $form += '<input name="villageId" value="'+villageId+'" >';
                $form += '<input name="name" value="'+name+'" >';
                $form += '</form>';
                if($(document).find('#export_form').length){
                    $(document).find('#export_form').remove();
                }
                $(document.body).append($form);
                // 提交表单，实现下载
                $(document).find('#export_form').submit();
            });


            // 表单提交
            $('.save-btn').on('click', function () {
                //var _form = $('#ajax-form');
                var _this = $(this);
                var form = this.form;

                if(form.memberType.value.trim() == 1) {
                    if(form.villageId.value == '0' && form.townId.value == '0') {
                        layer.msg('请选择乡镇');
                        return;
                    }
                }
                if(form.name.value.trim()=='') {
                    layer.msg('姓名不能为空');
                    form.name.focus();
                    return;
                }
                if(form.identityNumber.value.trim()=='') {
                    layer.msg('身份证号不能为空');
                    form.identityNumber.focus();
                    return;
                }
                /*if(!checkIdentity(form.identityNumber.value)){
                    layer.msg('身份证号格式不正确');
                    form.identityNumber.focus();
                    return;
                }*/
                $checkIdentity = identityCodeValid(form.identityNumber.value);
                if(!$checkIdentity.code){
                    layer.msg($checkIdentity.msg);
                    form.identityNumber.focus();
                    return;
                }
                var mobile = $('#mobile').val();

                /*if(mobile.trim() == ''){
                    layer.msg('手机号不能为空');
                    form.mobile.focus();
                    return;
                }*/
                if(mobile){
                    var mobile_reg = /^1(3|4|5|6|7|8)[0-9]\d{8}$/;
                    if(!mobile_reg.test(mobile)){
                        layer.msg('手机号格式不正确');
                        return;
                    }
                }
                var identityNumber = $('#identityNumber').val();
                var ori_identityNumber = $('#identityNumber').attr('data-identityNumber');

                if(identityNumber != ori_identityNumber){
                    var url = checkNum_url;
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: {'identityNumber': identityNumber},
                        dataType : 'json',
                        success: function (data) {
                            if(data.status == 1){
                                layer.msg('该身份证号已经存在！');
                                $('#identityNumber').focus();
                                return false;
                            }else{
                                submitForm(_this);
                            }
                        }
                    });
                    return false;
                }

                submitForm(_this);
            });
        }
    };

}();


//'use strict';

$(function() {
    Member.init();

});



/**
 * 身份证号格式验证
 */
function checkIdentity(identity){
    var reg = /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/;
    if(reg.test(identity)){
        return true;
    }else{
        return false;
    }
}

/**
 * 身份证号合法性验证
 * 支持15位和18位身份证号
 * 支持地址编码、出生日期、校验位验证
 */
function identityCodeValid(code) {
    var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
    var tip = "";
    var pass= true;

    if (!code || !/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/i.test(code)) {
    //if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
        tip = "身份证号格式错误";
        pass = false;
    } else if(!city[code.substr(0,2)]) {
        tip = "地址编码错误";
        pass = false;
    } else {
        // 15位转18位
        if(code.length == 15){
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var cardTemp = 0, i;
            // 18 或者 19
            code = code.substr(0, 6) + '19' + code.substr(6, code.length - 6);
            for(i = 0; i < 17; i ++)
            {
                cardTemp += code.substr(i, 1) * arrInt[i];
            }
            code += arrCh[cardTemp % 11];
        }
        // 18位身份证需要验证最后一位校验位
        if(code.length == 18){
            code = code.split('');
            //∑(ai×Wi)(mod 11)
            //加权因子
            var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
            //校验位
            var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
            var sum = 0;
            var ai = 0;
            var wi = 0;
            for (var i = 0; i < 17; i++)
            {
                ai = code[i];
                wi = factor[i];
                sum += ai * wi;
            }
            var last = parity[sum % 11];
            if(parity[sum % 11] != code[17]){
                tip = "校验位错误";
                pass =false;
            }
        }
    }
    //if(!pass) alert(tip);
    //return pass;
    return {'code':pass,'msg':tip};
}